module D {
    export class App{
        /** 网络对象 */
        public static net:Net;
        /** 用户基本信息 */
        public static userData:UserData;
        /** 桌子信息 */
        public static table:Table;
        /** 当前房间信息 */
        public static roomData:RoomData;
        /** 房间列表 */
        public static roomList:Array<RoomData>;
        /** 当前游戏场景 */
        public static gameView:V.GameView;
        /** 进度面板 */
        public static loadView:V.LoadView;
        /** 场景对象 */
        public static stage:egret.Stage;
        /** 窗口界面 */
        private static win:egret.Sprite;

        /** 初始化信息 */
        public static init(s:egret.Stage){
            App.userData = new UserData();
            App.table = new Table();
            App.gameView = null;
            App.loadView = new V.LoadView();
            App.stage = s;
            App.net = new Net();
            App.net.connect("ws://logon.hjy510.com:8099");
            App.win = new egret.Sprite();
            App.roomList = [];

            RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, App.onResComplete, App);
            RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, App.onResError, App);
            RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, App.onResProgress, App);

            // //添加MovieClip支持纹理的rotated
            // let fun = egret.MovieClip.prototype.$render;
            // egret.MovieClip.prototype.$render = function(){
            //     if(this["frames"][this["currentFrame"] - 1].rotated) this.$renderNode["rotated"] = true;
            //     else this.$renderNode["rotated"] = false;
            //     fun.call(this);
            // };
            // //添加sheet纹理集支持rotated
            // RES.SheetAnalyzer.prototype["parseSpriteSheet"] = function (texture, data, name) {
            //     var frames = data.frames;
            //     if (!frames) {
            //         return null;
            //     }
            //     var spriteSheet = new egret.SpriteSheet(texture);
            //     var textureMap = this.textureMap;
            //     for (var subkey in frames) {
            //         var config = frames[subkey];

            //         var texture_1 = new egret.Texture();
            //         if (config.offX === void 0) { config.offX = 0; }
            //         if (config.offY === void 0) { config.offY = 0; }
            //         if (config.sourceW === void 0) {
            //             config.sourceW = config.offX + config.w;
            //         }
            //         if (config.sourceH === void 0) {
            //             config.sourceH = config.offY + config.h;
            //         }
            //         texture_1._bitmapData = spriteSheet.$texture._bitmapData;
            //         texture_1.$initData(spriteSheet["_bitmapX"] + config.x, spriteSheet["_bitmapY"] + config.y, config.w, config.h, config.offX, config.offY, config.sourceW, config.sourceH, spriteSheet.$texture._sourceWidth, spriteSheet.$texture._sourceHeight, config.rotated);
            //         spriteSheet._textureMap[subkey] = texture_1;

            //         if (config["scale9grid"]) {
            //             var str = config["scale9grid"];
            //             var list = str.split(",");
            //             texture_1["scale9Grid"] = new egret.Rectangle(parseInt(list[0]), parseInt(list[1]), parseInt(list[2]), parseInt(list[3]));
            //         }
            //         if (textureMap[subkey] == null) {
            //             textureMap[subkey] = texture_1;
            //             if (name) {
            //                 this.addSubkey(subkey, name);
            //             }
            //         }
            //     }
            //     return spriteSheet;
            // };
            // let Ifun = eui.Image.prototype["parseSource"];
            // eui.Image.prototype["parseSource"] = function(){
            //     Ifun.call(this);
            //     if(this.texture) this.$renderNode["rotated"] = this.texture.$rotated;
            // }
        }

        /** 服务器连接成功 */
        public static onConnect(){
            console.log("onConnect");
            D.App.userData.login();
        }

        /** 接收到数据 */
        public static onMessage(msg: any = null):void{
            switch(msg[0]){
                case 1:{ //用户信息
                    App.userData.onMessage(msg);
                    break;
                }case 2:{ //房间消息
                    RoomData.onMessage(msg);
                    break;
                }case 6:{ //同步桌子状态
                    if(msg[1] == 100) App.table.gameStatus = msg[2].bGameStatus;
                    else if(msg[1] == 101) App.gameView && App.gameView.onSyncData(msg[2]);
                    else if(msg[1] == 255) console.log(msg);
                    break;
                }case 8:{ //桌子消息
                    App.table.onMessage(msg);
                    break;
                }case 9:{ //游戏消息
                    if(App.gameView) App.gameView.onNetData(msg[1], msg[2]);
                    break;
                }
            }
        }

        /** 显示窗口 */
        public static showWin(w:eui.Component):void{
            w.x = (App.stage.stageWidth - w.width) / 2;
            w.y = (App.stage.stageHeight - w.height) / 2;
            App.win.addChild(w);
        }
        /** 移除窗口 */
        public static removeWin(w:eui.Component):void{
            App.win.removeChild(w);
        }

        /** 显示大厅 */
        private static loadN = 0;
        public static showMain():void{
            App.loadN++;
            if(App.loadN == 2){
                App.stage.addChild(new V.MainScene());
                App.stage.addChild(App.win);
            }
        }

        /** 需要加载的资源数组 */
        private static res:string[];
        /** 切换场景 */
        public static enterGame(gV:V.GameView):void{
            // for(let i=0;scene.Res && i<scene.Res.length;i++){
            //     await RES.loadGroup(scene.Res[i]);
            // }
            App.res = gV.Res.slice();
            App.gameView = gV;
            App.loadView.setResNum(App.res.length);
            App.loadRes();
        }

        /** 资源加载完成 */
        public static onResComplete(e:RES.ResourceEvent):void{
            console.log("onResComplete", e.groupName);
            App.loadRes();
        }
        /** 加载资源 */
        public static loadRes():void{
            if(!App.res) return;
            App.stage.addChild(App.loadView);
            App.loadView.update(0, 100);
            if(App.res.length){
                RES.loadGroup(App.res.shift());
            }else{
                App.stage.removeChild(App.loadView);
                App.stage.addChildAt(App.gameView, App.stage.numChildren - 1);
                App.table.enterGame();
                App.res = null;
            }
        }

        /** 资源加载错误 */
        public static onResError(e:RES.ResourceEvent):void{
            console.log("onResError", e.groupName, e.itemsLoaded, e.itemsTotal);
            App.loadRes();
        }

        /** 资源加载进度 */
        public static onResProgress(e:RES.ResourceEvent):void{
            App.loadView.update(e.itemsLoaded, e.itemsTotal);
        }

        /** 二进制到json对象 */
        public static b2j(d:egret.ByteArray, m:any, j:any = null):any{
            let json = j || {};
            for(let i=0;i<m.length;i++){
                if(typeof(m[i][0]) != "string"){
                    if(m[i][2] == "A"){
                        json[m[i][1]] = App.b2j(d, m[i][0], []);
                    }else{
                        json[m[i][1]] = App.b2j(d, m[i][0]);
                    }
                }else if(m[i][0] == "A"){
                    let ar = [];
                    if(typeof(m[i][2]) == "number"){
                        for(let j=0;j<m[i][2];j++){
                            ar.push(App.b2d(d, m[i][3]));
                        }
                    }else{
                        ar.push(App.b2j(d, m[i][0]));
                    }
                    if(Array.isArray(json)){
                        json.push(ar);
                    }else{
                        json[m[i][1]] = ar;
                    }
                }else{
                    json[m[i][1]] = App.b2d(d, m[i][0]);
                }
            }
            return json;
        }
        /** 二进制根据类型读数据 */
        public static b2d(d:egret.ByteArray, t:string):any{
            switch(t){
                case "B":{
                    return d.readUnsignedByte();
                }case "S":{
                    return d.readUnsignedShort();
                }case "I":{
                    return d.readUnsignedInt();
                }case "L":{
                    let l = d.readInt();
                    d.readInt();
                    return l;
                }case "F":{
                    return d.readFloat();
                }
            }
        }
        /** 创建二进制对象 */
        public static createBin(m:number,s:number,len:number):egret.ByteArray{
            let sd = new egret.ByteArray(null, 8+len);
            sd.endian = egret.Endian.LITTLE_ENDIAN;
            sd.writeUnsignedShort(8+len);
            sd.writeUnsignedShort(0);
            sd.writeUnsignedShort(m);
            sd.writeUnsignedShort(s);
            return sd;
        }
        /** 获取动画 */
        public static getMovieClip(n:string, nm:string):egret.MovieClip{
            let json = RES.getRes(n + "_json"), png = RES.getRes(n + "_png");
            if(json && png){
                let mcFactory:egret.MovieClipDataFactory = new egret.MovieClipDataFactory(json, png);
                let mcd = mcFactory.generateMovieClipData(nm);
                if(mcd == null) return null;
                else return new egret.MovieClip(mcd);
            }else{
                return null;
            }
        }
    }
}